import { ref, onMounted } from 'vue'

export interface Company {
  id: number
  name: string
  comment: string
}

function buildQuery(params?: Record<string, any>): string {
  if (!params) return ''
  const query = Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&')
  return query ? `?${query}` : ''
}

export function useFetchCompanies(
  baseUrl: string,
  params?: Record<string, any>
) {
  const companies = ref<Company[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  async function fetchCompanies() {
    loading.value = true
    error.value = null
    try {
      const url = `${baseUrl}/api/company/list${buildQuery(params)}`
      const res = await fetch(url)
      if (!res.ok) throw new Error('网络错误')
      const data = await res.json()
      companies.value = data
    } catch (e: any) {
      error.value = e.message || '未知错误'
    } finally {
      loading.value = false
    }
  }

  onMounted(fetchCompanies)

  return { companies, loading, error, fetchCompanies }
}
